package com.example.ymm.modules1.controller.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.controller.BaseController;
import com.example.ymm.modules1.entity.my.user.*;
import com.example.ymm.modules1.query.DbTestNoteQueryCriteria;
import com.example.ymm.modules1.service.dto.*;
import com.example.ymm.modules1.service.user.*;
import com.example.ymm.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/hl/user/book")
@Api(tags = "用户端 书本信息接口")
@Slf4j
@CrossOrigin
public class UserBookController extends BaseController {

    @Autowired
    DbBookService dbBookService;
    @Autowired
    DbUserNoteService dbUserNoteService;

    @Autowired
    DbReadLogService dbReadLogService;

    @Autowired
    DbIntegralLogService dbIntegralLogService;

    @Autowired
    DbCardService dbCardService;

    @Autowired
    DbErrorService dbErrorService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    DbTestNoteService dbTestNoteService;

    @Autowired
    DbFileService dbFileService;

    @ApiOperation(value = "书本列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public CommonResult list(@Valid DbClazzBookQueryCriteria criteria) {
        try{
            List<ViewBook> list = dbBookService.getUserBook(criteria);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "书本列表")
    @RequestMapping(value = "/allList", method = RequestMethod.POST)
    public CommonResult allList(@Valid DbBookQueryCriteria criteria) {
        try{
            List<DbBook> list = dbBookService.queryAll(criteria);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "书本列表(分页)")
    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    public CommonResult pageList(@Valid DbBookQueryCriteria criteria, YmPageDto ymPage) {
        try{
            TableList<DbBook> list = dbBookService.list(criteria, ymPage);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "详情")
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public CommonResult detail(@ApiParam(value = "数据主键") @RequestParam(required = true) String bookId) {
        try{
            DbBook book = dbBookService.detail(bookId);
            return CommonResult.success(book);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "书本阅读")
    @RequestMapping(value = "/readBook", method = RequestMethod.POST)
    public CommonResult readBook(@ApiParam(value = "数据主键") @RequestParam(required = true) String bookId) {
        try{
            DbBook book = dbBookService.readBook(bookId);

            return CommonResult.success(book);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "我的笔记列表(默认查今日)")
    @RequestMapping(value = "/noteList", method = RequestMethod.POST)
    public CommonResult noteList(@Valid DbUserNoteQueryCriteria criteria,YmPageDto ymPage) {
        try{
            String dates = DateKit.dateFormat(new Date(), "yyyy-MM-dd");
            List<String> times = dbUserNoteService.getTimes(dates);
            criteria.setCreateTime(times);
            TableList<DbUserNote> list = dbUserNoteService.list(criteria, ymPage);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "我的书本笔记-根据书本id列出这本书的所有笔记")
    @RequestMapping(value = "/getNotesByBookId", method = RequestMethod.POST)
    public CommonResult getNotesByBookId(String bookId,String userId) {
        try{
            List<JSONObject> list = dbUserNoteService.getNotesByBookId(bookId,userId);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "笔记详情")
    @RequestMapping(value = "/noteDetail", method = RequestMethod.POST)
    public CommonResult noteDetail(String noteId) {
        try{
//            Map<String, Object> map = dbUserNoteService.addNote(dto);
            DbUserNote note = dbUserNoteService.getById(noteId);
            return CommonResult.success(note);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "提交笔记(日常打卡)")
    @RequestMapping(value = "/addNoteBatch", method = RequestMethod.POST)
    public CommonResult addNoteBatch(String list) {
        try{
            String userId = getUserId();
            boolean b = redisUtil.setIfAbsent(RedisKeyManager.user_lock_book + userId, "1", 2, TimeUnit.SECONDS);
            if(!b){
//                log.info("---提交录音进行限流1:"+getUserName());
                return CommonResult.error("录音已提交，请勿重复提交!");
            }
//            log.info("--录音提交:"+getUserName()+"--毫秒数:"+new Date().getTime());
            log.info("--正常打卡提交记录:"+list);
            List<DbUserNoteDto> arr = JSONArray.parseArray(list, DbUserNoteDto.class);
            Map<String, AddNoteResultDto> map = dbUserNoteService.addNoteBatch(arr);
            return CommonResult.success(map);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "补卡")
    @RequestMapping(value = "/patchNoteBatch", method = RequestMethod.POST)
    public CommonResult patchNoteBatch(String list,String date) {
        try{
            String userId = getUserId();
            boolean b = redisUtil.setIfAbsent(RedisKeyManager.user_lock_book + userId, "1", 2, TimeUnit.SECONDS);
            if(!b){
                log.info("---提交录音进行限流:"+getUserName());
                return CommonResult.error("录音已提交，请勿重复提交!");
            }
            List<DbUserNoteDto> arr = JSONArray.parseArray(list, DbUserNoteDto.class);
            if(UtilValidate.isEmpty(date)){
                throw new YmException("请选择打卡日期!");
            }
            Map<String, AddNoteResultDto> map = dbUserNoteService.patchNoteBatch(arr,date);
            return CommonResult.success(map);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "提前读书打卡")
    @RequestMapping(value = "/advanceNoteBatch", method = RequestMethod.POST)
    public CommonResult advanceNoteBatch(String list,String date) {
        try{
            String userId = getUserId();
            boolean b = redisUtil.setIfAbsent(RedisKeyManager.user_lock_book + userId, "1", 2, TimeUnit.SECONDS);
            if(!b){
                log.info("---提交录音进行限流:"+getUserName());
                return CommonResult.error("录音已提交，请勿重复提交!");
            }
            List<DbUserNoteDto> arr = JSONArray.parseArray(list, DbUserNoteDto.class);
            if(UtilValidate.isEmpty(date)){
                throw new YmException("请选择打卡日期!");
            }
            Map<String, AddNoteResultDto> map = dbUserNoteService.advanceNoteBatch(arr,date);
            return CommonResult.success(map);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "删除笔记")
    @RequestMapping(value = "/deleteNote", method = RequestMethod.POST)
    public CommonResult deleteNote(String noteId) {
        try{
            dbUserNoteService.deleteNote(noteId);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "增加读书记录")
    @RequestMapping(value = "/addReadLog", method = RequestMethod.POST)
    public CommonResult addReadLog(String bookId,String bookName) {
        try{
            dbReadLogService.addReadLog(bookId,bookName);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "获取最近的读书记录")
    @RequestMapping(value = "/getNewUserNote", method = RequestMethod.POST)
    public CommonResult getNewUserNote(DbUserNoteQueryCriteria queryCriteria) {
        try{
            String userId = getUserId();
            queryCriteria.setUserId(userId);
            DbUserNote newUserNote = dbUserNoteService.getNewUserNote(queryCriteria);
            return CommonResult.success(newUserNote);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "读书记录列表")
    @RequestMapping(value = "/readLogList", method = RequestMethod.POST)
    public CommonResult readLogList(@Valid DbReadLogQueryCriteria criteria,YmPageDto ymPage) {
        try{
//            TableList<DbUserNote> list = dbUserNoteService.list(criteria, ymPage);

            if(UtilValidate.isEmpty(criteria.getUserId())){
              String userId = getUserId();
              criteria.setUserId(userId);
            }
            TableList<DbUserNote> list = dbReadLogService.getReadList(criteria,ymPage);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "读书记录列表")
    @RequestMapping(value = "/userNoteList", method = RequestMethod.POST)
    public CommonResult userNoteList(@Valid DbUserNoteQueryCriteria criteria,YmPageDto ymPage) {
        try{

            if(UtilValidate.isEmpty(criteria.getDay())&&UtilValidate.isNotEmpty(criteria.getCreateTime())){
                List<String> createTime = criteria.getCreateTime();
                String s = createTime.get(0).split(" ")[0];
                criteria.setDay(s);
                criteria.setCreateTime(null);
            }

            TableList<DbUserNote> list = dbUserNoteService.list(criteria, ymPage);
//            String userId = getUserId();
//            criteria.setUserId(userId);
            return CommonResult.success(list,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "积分记录列表")
    @RequestMapping(value = "/integralList", method = RequestMethod.POST)
    public CommonResult integralList(@Valid DbIntegralLogQueryCriteria criteria,YmPageDto ymPage) {
        try{
            String userId = getUserId();
            criteria.setUserId(userId);
            TableList<DbIntegralLog> list1 = dbIntegralLogService.list(criteria, ymPage);
            return CommonResult.success(list1,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "获取缺卡日期列表")
    @RequestMapping(value = "/getLackCards", method = RequestMethod.POST)
    public CommonResult getLackCards() {
        try{
            List<String> lackCards = dbCardService.getLackCards();
            return CommonResult.success(lackCards,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "获取提前打卡日期列表")
    @RequestMapping(value = "/getAdvanceCards", method = RequestMethod.POST)
    public CommonResult getAdvanceCards() {
        try{
//            List<String> times = DateUtils.fourDayAfter();
            List<String> cards = dbCardService.getAdvanceCards();
            AdvanceCardsDto dto=new AdvanceCardsDto();
            dto.setTimes(cards);
            if(UtilValidate.isNotEmpty(cards)){
                dto.setNow(cards.get(0));
            }

            return CommonResult.success(dto,"获取成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "提交错误信息")
    @RequestMapping(value = "/submitError", method = RequestMethod.POST)
    public CommonResult submitError(DbError error) {
        try{
//            List<String> times = DateUtils.fourDayAfter();
            dbErrorService.addError(error);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "测试阅读记录列表")
    @RequestMapping(value = "/testNoteList", method = RequestMethod.POST)
    public CommonResult testNoteList(DbTestNoteQueryCriteria criteria, YmPageDto ymPage) {
        try{
            TableList<DbTestNote> list = dbTestNoteService.list(criteria, ymPage);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "添加测试阅读记录")
    @RequestMapping(value = "/addTestNote", method = RequestMethod.POST)
    public CommonResult addTestNote(DbTestNote note) {
        try{
            dbTestNoteService.addFn(note);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除测试阅读记录")
    @RequestMapping(value = "/deleteTestNote", method = RequestMethod.POST)
    public CommonResult deleteTestNote(String noteId) {
        try{
            dbTestNoteService.removeById(noteId);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "书本内容图片")
    @RequestMapping(value = "/fileList", method = RequestMethod.POST)
    public CommonResult fileList(DbFileQueryCriteria criteria, YmPageDto ymPage) {
        try{
            String userId = getUserId();
            criteria.setUserId(userId);
            criteria.setBookId(null);
            TableList<DbFile> list = dbFileService.list(criteria, ymPage);
            return CommonResult.success(list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "用户上传图片")
    @RequestMapping(value = "/addFile", method = RequestMethod.POST)
    public CommonResult addFile(@RequestParam("excel") MultipartFile file, DbFile dbFile) {
        try{
            String host = "http://220.161.77.66:10111";
            String uploadPath = "H:read_book_server";

            String dates = DateKit.dateFormat(new Date(), "yyyy-MM-dd");
            String[] split = file.getOriginalFilename().split("\\.");
            String localFileName=UuidUtils.getUUID()+"."+split[1];
            String savePath= "/app_file/images/user/" + dates + "/" + localFileName;
            String path = uploadPath + savePath;
//            log.info("--path::"+path);
            File destination = new File( path);
            if (!destination.getParentFile().exists()) {
                FileUtils.forceMkdirParent(destination); // 使用commons-io的工具类
            }
           // file.transferTo(destination);
            FileUtils.copyInputStreamToFile(file.getInputStream(),destination);
            String imgUrl=host+savePath;
            dbFile.setImgUrl(imgUrl);
            dbFileService.addFn(dbFile);
            return CommonResult.success(imgUrl);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除上传图片")
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public CommonResult deleteFile(String fileId) {
        try{
            dbFileService.deleteFn(fileId);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "导入读书记录")
    @RequestMapping(value = "/importUserNote", method = RequestMethod.POST)
    public CommonResult importUserNote(@RequestBody List<ImportUserNoteDto> list) {
        try{
            if(UtilValidate.isEmpty(list)){
                return CommonResult.error("数据不能为空!");
            }
            List<String> strings = dbUserNoteService.importUserNote(list);
            return CommonResult.success(strings);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }



}
